var respFun;
var tabID;
var comPort;

function login(session) {
    localStorage.session = JSON.stringify(session);
    FB.Auth.setSession(session, 'connected');
}




function setupLoginLogoutHandlers() {
  FB.Event.clear('auth.login');
  FB.Event.clear('auth.logout');

  onLogout(function() {
    chrome.tabs.onUpdated.addListener(checkForSuccessPage);
    checkForSuccessPage();
  });
}


function onLogin(cb) {
  FB.Event.subscribe('auth.login', function() {
    console.log("Now logged in");
    cb();
  });
  if(FB.getSession()) {
    console.log("Already logged in", FB.getSession());
    cb();
  }
}


function onLogout(cb) {
  FB.Event.subscribe('auth.logout', function() {
    cb();
  });
  if(!FB.getSession()) {
    cb();
  }
}


function isLoggedIn() {
  return FB.getSession();
}

function uid() {
  // Assumed to only be called when logged in
  return FB.getSession().uid;
}


function getProfilePic(cb) {
    FB.api({
      method: 'fql.query', query: 'SELECT url, pic_square FROM profile WHERE id=' + FB.getSession().uid
    },
    function(result) {
	cb(result[0].url, result[0].pic_square);
    });
}

function getExtensionInfo(cb) {
  sesh = localStorage.session;
  if (!sesh) {
    session = {
      'session_key':'none',
      'uid':'none',
    };
  }
  else {
    var session = JSON.parse(localStorage.session)
  }

    $.ajax({
	url: 'http://1-test.thejettube.appspot.com/getextensioninfo',
	data: {session_key: session.session_key,
	       id: session.uid},
	success: function(data) {
	         localStorage.userKey = data.key;
            cb(data);
        },
        dataType: 'json'});

}

function checkForSuccessPage() {
  if(!isLoggedIn()) {
    chrome.tabs.getAllInWindow(null, function(tabs) {
      for(var i = 0; i < tabs.length; i++) {
        if(tabs[i].url.indexOf(successURL) == 0) {
          // We found a match, now extract the login info and actually login
          var params = tabs[i].url.split('?')[1].split('&');
          var session = JSON.parse(unescape(params[0].split('=')[1]));
          login(session);
          getExtensionInfo(function(data) {
            comPort.postMessage(data);
          })
          chrome.tabs.onUpdated.removeListener(checkForSuccessPage);
        }
      }
    });
  }
}

function sendSong(vt,vid,sk)
{
  if (!localStorage.userKey) userKey = 'none';
  else {
    userKey = localStorage.userKey;
  }
  data = {
    'userKey': userKey,
    'station_key': sk,
    'songid': vid,
    'title': vt
  }
    $.ajax({
      url: 'http://1-test.thejettube.appspot.com/addsong',
      data: data,
      success: function(data) {
        addSongResponse(data);
      },
      dataType: 'json'
    });
}

function addSongResponse(data)
{
  respFun(data);
}


function jetRequest(msg,user,resp)
{
  if (msg.messageType == 'createDD') {
    getExtensionInfo(resp);
    return;
  }
  respFun = resp;
    videoTitle = msg.videoTitle;
    videoID = msg.videoID;
    stationKey = msg.stationKey;
    sendSong(videoTitle,videoID,stationKey);
}

chrome.extension.onRequest.addListener(jetRequest);

function addPort(port) {
    comPort = port;
}
chrome.extension.onConnect.addListener(addPort);


